package com.smartshopping.model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.smartshopping.iu.R;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.TextView;
 
public class DataBaseHelper extends SQLiteOpenHelper{
 
    //The address of our application, change the word package by package name of our app
    private static String DB_PATH = "";
 
    //The name of our data base file. It must be in our folder assets.
    private final static String DB_NAME = "mydb.sqlite";
 
    private SQLiteDatabase myDataBase; 
 
    private final Context myContext;
 
    /**
     * Constructor
     */
    public DataBaseHelper(Context context) {
    	super(context, DB_NAME, null, 1);
    	DB_PATH = "/data/data/" + context.getPackageName() + "/databases/"; 
        this.myContext = context;
    }	
 
    /**
     * Creates a empty sqlite database on the system and rewrites it with your own database.
     * */
    public void createDataBase(Context contexto) throws IOException{
    	//Check if the sqlite database already exists
    	boolean dbExist = checkDataBase();
    	if(dbExist){
    		//If our database exists, do nothing
    		System.out.println("database exists");
    	}else{
    		//If doesnt exists this method creates an empty database into the default system path
        	this.getReadableDatabase();
        	try {
        		//Copy our database.sqlite into the new database
    			copyDataBase();
    		} catch (IOException e) {
        		throw new Error("Error copying database");
        	}
    	}
    }
 
    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    public boolean checkDataBase(){
    	SQLiteDatabase checkDB = null;
    	try{
    		String myPath = DB_PATH + DB_NAME;
    		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    	}catch(SQLiteException e){
    		//database does't exist yet.
    		System.out.println("database does't exist");
    		return false;
    	}
    	if(checkDB != null){
    		checkDB.close();
    	}
    	return checkDB != null ? true : false;
    }
 
 
    /**
 
     * Copies your database from your local assets-folder to the just created empty database
     * */
    private void copyDataBase() throws IOException{
    	//Open your local db as the input stream
    	InputStream myInput = myContext.getAssets().open(DB_NAME);
    	// Path to the just created empty db sqlite android
    	String outFileName = DB_PATH + DB_NAME;
    	//Open the empty db as the output stream
    	OutputStream myOutput = new FileOutputStream(outFileName);
    	//transfer bytes from the inputfile to the outputfile
    	byte[] buffer = new byte[1024];
    	int length;
    	while ((length = myInput.read(buffer))>0){
    		myOutput.write(buffer, 0, length);
    	}
    	//Close the streams
    	myOutput.flush();
    	myOutput.close();
    	myInput.close();
 
    }
 
    /**
     * Open the database
     * @throws SQLException
     */
    public void openDataBase() throws SQLException{
        String myPath = DB_PATH + DB_NAME;
    	myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
 
    }
 
    @Override
	public synchronized void close() {
    	    if(myDataBase != null)
    		    myDataBase.close();
    	    super.close();
	}
 
	@Override
	public void onCreate(SQLiteDatabase db) {
	}
 
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
	
	//Get READER information from database (tu viet)
	public SQLiteDatabase getReaderInformationDatabase()
	{
		SQLiteDatabase db = this.getReadableDatabase();
		return db;
	}
	
	//Get WRITER information from database (tu viet)
	public SQLiteDatabase getWriterInformationDatabase()
	{
		SQLiteDatabase db = this.getWritableDatabase();
		return db;
	}
	
	//Deleta odl database
	public void delDatabase()
	{
		File file = new File(DB_PATH + DB_NAME);
		boolean deleted = file.delete();
	}
}